<?php

namespace app\admin\service;


use app\admin\model\User as UserModel;
use app\admin\util\StringUtil;
use think\facade\Db;

class UserService
{
    protected $model;
    protected $tokenService;

    public function __construct()
    {
        $this->model = app()->make(UserModel::class);
        $this->tokenService = app()->make(TokenService::class);
    }

    /**
     * 用户给登录
     *
     * @param $username
     * @param $password
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function doLogin($username, $password): ?UserModel
    {
        $user = $this->model->where('username', $username)->find();
        if ($this->checkPassword($user, $password)) {
            return $user;
        }
        return null;
    }

    /**
     * 查询uid
     *
     * @return int|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function queryUid(): ?int
    {
        $token = cookie("token");
        return $this->tokenService->queryUidByToken($token);
    }

    /**
     * 查询user
     *
     * @return array|mixed|Db|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function queryUser()
    {
        $token = cookie("token");
        return Db::table('pre_admin_user')->alias('u')->join('pre_token t', 'u.id=t.uid')->where('t.token', $token)->field('u.id, u.username,u.nickname,u.salt,u.password')->find();
    }

    /**
     * 修改用户信息
     *
     * @param $data
     * @param $where
     * @return bool|null
     */
    public function updateUser($data, $where): ?bool
    {
        return $this->model->where($where)->save($data);
    }

    /**
     * 校验密码
     *
     * @param $user
     * @param $password
     * @return bool
     */
    public function checkPassword($user, $password): ?bool
    {
        return $user != null && $user['password'] === StringUtil::getPassword($password, $user['salt']);
    }
}